﻿using Models.Common;
using MQTTnet.Client;
using MQTTnet.Protocol;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using UtilsBase;
using UtilsCache;
using UtilsMQ;
using UtilsMQ.Model;

namespace MqttClient
{

    public class test : MqttClientService
    {

        public test()
        {
            _topic = "mq_topictest";

        }
        public void start()
        {
            new test().MqttClientStart();
            Thread.Sleep(1000);
            while (true)
            {
                Publish("mq_topic111", DateTime.Now.ToString());

                Thread.Sleep(1000 * 10);
            }
            Console.WriteLine("已发送");
        }
        /// <summary>
        /// 收到消息事件
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        public override Task _mqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {
            Console.WriteLine($"收到消息事件ApplicationMessageReceivedAsync：客户端ID=【{arg.ClientId}】接收到消息。Topic主题=【{arg.ApplicationMessage.Topic}】 消息=【{Encoding.UTF8.GetString(arg.ApplicationMessage.Payload)}】 qos等级=【{arg.ApplicationMessage.QualityOfServiceLevel}】");

            //这里不要新线程了，因为后面用到的handleEventLists线程不生效，跨线程用不了
            string message = Encoding.UTF8.GetString(arg.ApplicationMessage.PayloadSegment);

            return Task.CompletedTask;
        }

        public bool sendMsg(string topic, string data)
        {
            return new MqttClientService().Publish(topic, data);
        }
    }
}
